package com.md.value.html;

import com.google.common.collect.Lists;
import com.md.model.html.LabelStyle;
import com.md.util.ObjectUtil;
import com.md.util.POIUtil;
import lombok.Getter;
import org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;

import java.util.List;
import java.util.Optional;

import static com.md.util.POIUtil.getBlob;
import static com.md.util.POIUtil.getItalic;

/**
 * @author 刘骄阳
 * 2024-06-18 10:59
 */
@Getter
public class Font {

  private LabelStyle fontFamily;
  private LabelStyle fontSize;
  private LabelStyle fontWeight;
  private LabelStyle fontStyle;
  private LabelStyle fontColor;
  private LabelStyle textDecoration;
  private LabelStyle backgroundColor;

  public Font(final CTRPr rPr, final List<ThemeDocument> themeDocuments) {
    if (rPr == null) {
      return;
    }
    // 字体风格
    POIUtil.getFontFamily(rPr, themeDocuments).ifPresent(labelStyle -> fontFamily = labelStyle);
    // 字体大小
    POIUtil.getFontSize(rPr).ifPresent(labelStyle -> fontSize = labelStyle);
    // 加粗
    getBlob(rPr).ifPresent(labelStyle -> fontWeight = labelStyle);
    // 倾斜
    getItalic(rPr).ifPresent(labelStyle -> fontStyle = labelStyle);
    // 字体颜色
    POIUtil.getColor(rPr).ifPresent(labelStyle -> fontColor = labelStyle);
    // 下划线、删除线
    POIUtil.getTextDecoration(rPr).ifPresent(labelStyle -> textDecoration = labelStyle);
    // 背景色
    getBackgroundColor(rPr).ifPresent(labelStyle -> backgroundColor = labelStyle);
  }

  public List<LabelStyle> getLabelStyle() {
    List<LabelStyle> labelStyles = Lists.newArrayList();
    Optional.ofNullable(fontFamily).ifPresent(labelStyles::add);
    Optional.ofNullable(fontSize).ifPresent(labelStyles::add);
    Optional.ofNullable(fontWeight).ifPresent(labelStyles::add);
    Optional.ofNullable(fontStyle).ifPresent(labelStyles::add);
    Optional.ofNullable(fontColor).ifPresent(labelStyles::add);
    return labelStyles;
  }


  private Optional<LabelStyle> getBackgroundColor(final CTRPr rPr) {
    return Optional.ofNullable(rPr.getShdArray()).map(shdArray -> {
      if (ObjectUtil.isEmpty(shdArray)) {
        return null;
      }
      CTShd ctShd = shdArray[0];
      return LabelStyle.of(LabelStyleType.BACKGROUND_COLOR, POIUtil.getColor(ctShd.xgetColor(),
        ColorIndex.BLACK.getHex()));
    });
  }
}
